// pages/settings/settings.js
import { Product } from 'product-model.js'
var product = new Product();
//获取应用实例
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    productDetail: null,
    current: 0,//当前进度条位置
    percent: 0,//轮播图总长度
    ctrnum: 0,//当前选中购买数量
    stockNum: null,//共有衣服件数
    specsName: "",//选择尺寸
    isShowPopup: false,
    tip: "",
    cartNum: 0,
    animate: false//购物车动画
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.aldstat.sendEvent('进入商品详情页面');
    let id = options.id;
    let storeNo = options.storeNo || wx.getStorageSync('storeNo');;
    this.setData({
      storeNo,
      goodsId: id
    });
    wx.showLoading({
      title: '加载中...',
    })
    //判断用户是否登录
    let userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({
        userInfo: userInfo
      });
    }
    this._loadData();
  },
  _loadData(cb) {
    this.getGoodDetail(cb);
    this.getCart();
  },
  //获取商品详情
  getGoodDetail(cb) {
    let { storeNo, goodsId } = this.data;
    let parames = {
      "storeNo": storeNo.toString(),
      "goodsId": goodsId.toString()
    };
    let that = this;

    product.getGoodsById(parames, res => {
      if (res.status) {
        let data = res.data;

        let percent = data.goodsImages.length;//设置滚动条
        let goodsId = data.goodsId;
        data.goodsColour.forEach((value, index) => {
          if (value.goods_id == goodsId) {
            value.isSelected = true;
          }
        })

        that.setData({
          productDetail: data,
          percent,
          loadingHidden: true
        })
        wx.setNavigationBarTitle({
          title: res.data.brandName
        })
        cb && cb();
        wx.hideLoading();
      }
    });
  },
  //获取购物车数据
  getCart(cb) {
    let that = this;
    let { storeNo } = this.data;
    let userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      let parames = {
        "userId": this.toString(userInfo.id),
        "storeNo": this.toString(storeNo)
      }
      product.getCart(parames, res => {
        if (res.status) {
          let total = 0;
          res.data.forEach((value, index) => {
            total += parseInt(value.goodsNum);
          })

          that.setData({
            "cartNum": total
          })
          cb && cb();
          //设置购物车右上角红色点
          wx.setTabBarBadge({
            index: 1,
            text: '' + total,
          })
        }
      })
    }

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading(); //在标题栏中显示加载图标 
    this._loadData(() => {
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();            //停止下拉刷新 
    })

  },
  onColorOption: function (e) {
    let goodsId = product.getDataSet(e, "goodid");
    let curGoodsId=this.data.productDetail.goodsId;
    if (curGoodsId != goodsId){
      this.setData({
      "goodsId": goodsId,
      stockNum:null
    });
    this.getGoodDetail();
    }
    
  },
  onHeadChange(e) {
    let current = e.detail.current;
    this.setData({
      current
    })
  },
  onSizeOption(e) {
    let id = product.getDataSet(e, "id");
    let { productDetail, ctrnum } = this.data;
    let stockNum = 0;
    let specsName = "";
    productDetail.goodsStock.forEach((value, index) => {
      if (value.id == id) {

        value.isSelected = value.isSelected ? false : true;
        if (value.isSelected){
          stockNum = value.stockNum;
          specsName = value.specsName;
          if (ctrnum <= 0) {
            ctrnum = 1;
          }
        }else{
          stockNum = 0;
          specsName = "";
        }
      } else {
        value.isSelected = false;
      }
    });

      if (ctrnum > stockNum) {
        ctrnum = stockNum
      }
    
      this.setData({
        "productDetail.goodsStock": productDetail.goodsStock,
        stockNum,
        specsName,
        ctrnum
      })

  },
  //加入购物车
  onAddCart(e) {
    let that = this;
    app.aldstat.sendEvent('加入预购清单-商品详情');
    let userInfo = wx.getStorageSync('userInfo');
    //此处需要判断用户是否存在
    this.getUserInfo(userInfo);
    let { storeNo, productDetail, ctrnum, specsName } = this.data;
    if (userInfo) {
      let parames = {
        "userId": this.toString(userInfo.id),
        "storeNo": this.toString(storeNo),
        "goodsId": this.toString(productDetail.goodsId),
        "goodsName": this.toString(productDetail.goodsName),
        "goodsPic": this.toString(productDetail.goodsPic),
        "goodsPrice": this.toString(productDetail.discountPrice),
        "originalPrice": this.toString(productDetail.goodsPrice),
        "goodsNum": this.toString(ctrnum),
        "goodsColor": this.toString(productDetail.goodsColor),
        "specsName": this.toString(specsName),
      }

      if (parames.specsName == "") {
        product.showMyTip({ _this: this, title: "请选择商品尺寸" });
        return;
      }
      if (parames.goodsNum == "0") {
        product.showMyTip({ _this: this, title: "商品数量不能为0" });
        return;
      }

      product.addCart(parames, res => {
        if (res.status) {
          wx.showToast({
            title: '加入购物车成功',
            icon: 'success',
            duration: 2000
          })
          that.getCart(() => {
            that.setData({
              animate: true
            });

            setTimeout(() => {
              that.setData({
                animate: false
              });
            }, 500)
          });

        } else {
          product.showMyTip({ _this: this, title: "加入购物车失败" });
        }
      })
    }
  },
  //进入购物车
  goCart() {
    wx.switchTab({
      url: '/pages/cart/cart'
    })
  },
  //去付款
  onOrderConfirm(e) {
    let userInfo = this.data.userInfo || wx.getStorageSync('userInfo');
    //此处需要判断用户是否存在
    this.getUserInfo(userInfo);
    let { productDetail, specsName, ctrnum,} = this.data;
    if (userInfo){
      let result = [];
      
          result.push({
            "userId": this.toString(userInfo.id),
            "storeNo": this.toString(userInfo.storeNo),
            "specsName": this.toString(specsName),
            "goodsId":  this.toString(productDetail.goodsId)
          });

          if (result[0].specsName == "") {
            product.showMyTip({ _this: this, title: "请选择商品尺寸" });
            return;
          }
  
      let params = {
          "userId": ''+ userInfo.id,
          "storeNo": userInfo.storeNo,
          "goodsId": '' + productDetail.goodsId,
          "goodsName": productDetail.goodsName,
          "goodsNum": '' + ctrnum,
          "goodsPrice": '' + productDetail.goodsPrice,
          "goodsColor": productDetail.goodsColor,
          "specsName": specsName,
          "goodsPic": productDetail.goodsPic
      };
      console.log(params)
      product.nowBuy(params, res => {
        if (res.status) {
          
            wx.navigateTo({
                url: "/pages/orderDetail/orderDetail?orderId=" + res.data.orderId
            })
        }
      })
    }
    

  },
  //判断用户信息是否存在
  getUserInfo(userInfo) {
    if (!userInfo) {
      let parames = {
        _content: "请先完成登录",
        confirm: () => {
          wx.navigateTo({
            url: '/pages/login/login',
          })
        },
        cancel: () => {
          return;
        }
      }
      product.showModal(parames);
    } else {
      this.setData({
        userInfo: userInfo
      });
    }
  },
  toString(parames) {
    if (parames != null && parames != "") {
      return parames.toString();
    } else {
      return "";
    }
  },
  onNumMinus(e) {
    let ctrnum = this.data.ctrnum;
    if (ctrnum > 1) {
      ctrnum--;
      this.setData({
        ctrnum
      })
    } else {
      return;
    }
  },
  onNumAdd(e) {
    let { ctrnum, stockNum, specsName} = this.data;

    if (specsName == "") {
      product.showMyTip({ _this: this, title: "请选择商品尺寸" });
      return;
    }

    if (ctrnum < stockNum) {
      ctrnum++;
      this.setData({
        ctrnum
      })
    } else {
      product.showMyTip({ _this: this, title: "数量已达上限" });
      return;
    }
  },
//   预览图片
  preImg(e){
      let goodsImages = this.data.productDetail.goodsImages
      let now = product.getDataSet(e, "src")
      let imgList = []
      if (goodsImages || goodsImages.length > 0){
        goodsImages && goodsImages.forEach(val=>{
            imgList.push(val.url)
        })
        wx.previewImage({
            current: now, // 当前显示图片的http链接
            urls: imgList// 需要预览的图片http链接列表
        })
      }
  }

})